package top.chatgqt.SmartChargeStation.demo.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender;
import jakarta.annotation.PreDestroy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import top.chatgqt.SmartChargeStation.demo.netty.handlers.ImoocClientProtobufHandler;

import java.util.concurrent.TimeUnit;

/*
 * Netty客户端引导器和服务端的不同
 *
 * 1. 客户端只需要1个NioEventLoopGroup
 *    服务端需要2个NioEventLoopGroup
 *
 * 2. 客户端的引导器是Bootstrap
 *    服务端的引导器是ServerBootstrap
 *
 * 3. 客户端的Channel类型是 NioSocketChannel
 *    服务端的Channel类型是 NioServerSocketChannel
 *
 * 4. 客户端的Channel初始化方法是handler()
 *    服务端的Channel初始化方法是childHandler()
 *
 * 5. 客户端的bind()需要传入服务端的地址和端口号
 *    服务端的bind()只需要传入服务端的端口号
 */
@Slf4j
@Component
@Order(2)
public class NettyClient implements CommandLineRunner {

    private NioEventLoopGroup workerGroup;
    private ChannelFuture future;

    @Value("${Netty.server.port}")
    private int port;
    @Value("${Netty.server.host}")
    private String host;

    @Async
    @Override
    public void run(String... args) {
        try {
            this.start();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * Netty启动
     */
    private void start() {

        // 处理网络IO
        workerGroup = new NioEventLoopGroup();


        Bootstrap bootstrap = new Bootstrap();
        bootstrap
                // 配置NioEventLoop组件
                .group(workerGroup)
                // 配置Channel组件
                .channel(NioSocketChannel.class)
                // 将ChannelHandler添加到ChannelInitializer
                .handler(new ChannelInitializer<>() {

                    // Channel初始化
                    @Override
                    protected void initChannel(Channel channel) throws Exception {
                        /*
                        Channel初始化是伴随ChannelPipeline的初始化
                         */

                        //  获取 ChannelPipeline
                        ChannelPipeline pipeline = channel.pipeline();

                        /*
                        真正进行业务逻辑处理
                         */
                        //ByteBuf delimiter = Unpooled.copiedBuffer("$_", CharsetUtil.UTF_8);
                        pipeline
                                //.addLast(new DelimiterBasedFrameDecoder(1024, delimiter))
                                // 固定数据包长度解决粘包半包问题
//                                .addLast(new FixedLengthFrameDecoder(11))
                                // 编码器
                                //.addLast(new StringEncoder())
                                // 添加处理器
//                                .addLast(new ImoocClientHandler());

                                //.addLast(new ImoocClientPkgHandler());

                                .addLast(new ProtobufVarint32LengthFieldPrepender())
                                .addLast(new ProtobufEncoder())
                                .addLast(new ImoocClientProtobufHandler());
                    }
                });

        doConnect(bootstrap);
    }

    private void doConnect(Bootstrap bootstrap) {
        try {
            log.info(">>>> Netty 客户端正在启动");
            future = bootstrap.connect(host, port).sync();

            // 注册监听器
            // 启动时 监听是否连接成功，不成功不断重试
            future.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture channelFuture) throws Exception {
                    if (channelFuture.isSuccess()) {
                        log.info(">>>> Netty 客户端连接成功");
                    } else {
                        log.info(">>>> Netty 客户端和服务端断开连接");
                        // 如果连接不上，单独启动一条线程重新连接
                        final EventLoop loop = channelFuture.channel().eventLoop();
                        loop.schedule(new Runnable() {
                            @Override
                            public void run() {
                                doConnect(bootstrap);
                            }
                        }, 10, TimeUnit.SECONDS);
                    }
                }
            });

            if (future != null) {
                future.channel().closeFuture().sync();
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            destroy();
        }
    }


    /**
     * Netty 关闭 释放资源
     */
    @PreDestroy
    private void destroy() {
        try {
            workerGroup.shutdownGracefully().sync();
            // 关闭通道（若已绑定成功）
            if (future != null && future.channel().isOpen()) {
                future.channel().close().sync();
            }
            log.info(">>>>  Netty 客户端资源已释放");
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}
